<?php
//连接数据库
include("config/config.php");
//操作内容跳转口
switch ($_POST['handle']) {

    case 'login':
        //跳转到登录
        echo login($dbh);
        break;
        //跳转到注册
    case 'regist':
        echo regist($dbh);
        break;
        //跳转到添加评论信息
    case 'comment':
        echo comment($dbh);
        break;
        //跳转到登出
    case 'logout':
        echo logout();
        break;
    case 'admin_logout':
        //后台登录
        echo admin_logout();
        break;
    case 'admin':
        //后台登录
        echo admin();
        break;
    case 'add':
        //后台添加用户
        echo add($dbh);
        break; 
    case 'dele':
        //后台删除用户
        echo dele($dbh);
        break;  
    case 'modify':
        //后台修改用户
        echo modify($dbh);
        break;   
    default:
        exit;
        break;
}

//登录
function login($dbh){
    //查询数据库
    $user=$dbh->query("SELECT * FROM user WHERE username='".$_POST['username']."' AND password='".md5($_POST['password'])."'")->fetchAll();
    //接口返回信息
    if($user){
        session_start();
        $_SESSION['username']=$_POST['username'];
        return "done";
    }
    else{
        return "no";
    }
}
//登出
function logout(){
    session_start();
    //销毁session
    unset($_SESSION['username']);
    return "done";
}

//注册
function regist($dbh){
    //添加数据库用户信息
    $count = $dbh->exec("INSERT INTO user SET username='".$_POST['username']."' ,name='".$_POST['name']."' , password='".md5($_POST['password'])."' ,time=NOW()");
    //接口返回信息
    if($count){
        return "done";
    }
}
//添加评论信息
function comment($dbh){
    //添加数据库评论信息
    $count = $dbh->exec("INSERT INTO comment SET name='".$_POST['name']."' ,content='".$_POST['comment']."' ,time=NOW()");
    //接口返回信息
    if($count){
        return "done";
    }
}

//删除用户信息
function dele($dbh){
    $count = $dbh->exec("DELETE FROM user WHERE id=".$_POST['id']);
    if($count){
        return "done";
    }
}
//添加用户信息
function add($dbh){
    $count = $dbh->exec("INSERT INTO user SET username='".$_POST['username']."' ,name='".$_POST['name']."' ,time=NOW()");
    if($count){
        return "done";
    }
}
//修改用户信息
function modify($dbh){
    $count = $dbh->exec("UPDATE user SET username='".$_POST['username']."' ,name='".$_POST['name']."' ,time=NOW() WHERE id='".$_POST['id']."'");
    if($count){
        return "done";
    }
}
//后台用户登录
function admin(){
    if($_POST['username']=="admin" && $_POST['password']=="admin"){
        session_start();
        $_SESSION['admin']="admin";
        return "done";
    }
}
//后台用户登出
function admin_logout(){
    session_start();
    //销毁session
    unset($_SESSION['admin']);
    return "done";
}